const { Chapter, Course } = require("../../models");
const { success, failure } = require("../../utils/responses");
const chaptersService = require("../../services/learn/chaptersService");

/**
 * 获取章节列表
 * @param req
 * @param res
 * @returns {Promise<void>}
 */
exports.list = async (req, res) => {
  try {
    const { count, rows, pageSize, currentPage } =
      await chaptersService.list(req);
    // 返回
    success(res, "章节查询成功", {
      lists: rows,
      pagination: {
        total: count,
        currentPage,
        pageSize,
      },
    });
  } catch (error) {
    failure(res, error);
  }
};

/**
 * 获取章节详情
 * @param req
 * @param res
 * @returns {Promise<void>}
 */
exports.details = async (req, res) => {
  try {
    const chapter = await chaptersService.getChapter(req);
    success(res, "查询章节成功", chapter);
  } catch (error) {
    failure(res, error);
  }
};

/**
 * 添加章节
 * @param req
 * @param res
 * @returns {Promise<void>}
 */
exports.add = async (req, res) => {
  try {
    const body = filterBody(req);
    const chapter = await chaptersService.create(body);
    success(res, "创建章节成功", chapter, 201);
  } catch (error) {
    failure(res, error);
  }
};

/**
 * 删除章节
 * @param req
 * @param res
 * @returns {Promise<void>}
 */
exports.del = async (req, res) => {
  try {
    await chaptersService.delete(req.body.id);
    success(res, "删除章节成功");
  } catch (error) {
    failure(res, error);
  }
};

/**
 * 更新章节
 * @param req
 * @param res
 * @returns {Promise<void>}
 */
exports.update = async (req, res) => {
  try {
    const body = filterBody(req);
    const chapter = await chaptersService.update(req.body.id, body); //删除
    success(res, "更新章节成功", chapter);
  } catch (error) {
    failure(res, error);
  }
};

/**
 * 公共方法过滤白名单
 * @param req
 * @returns {{title, content: (string|string|DocumentFragment|*)}}
 */
function filterBody(req) {
  return {
    courseId: req.body.courseId,
    title: req.body.title,
    content: req.body.content,
    rank: req.body.rank,
  };
}
